package com.aoxin.service.impl.opm;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import com.aoxin.model.activity.SlfRecommendMoneySale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.aoxin.mapper.opm.SlfUserLfbUpdateLogByRootMapper;
import com.aoxin.mapper.opm.SlfUserMapper;
import com.aoxin.model.activity.SlfRecommendMoney;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.dto.UserAndChildrenDto;
import com.aoxin.model.opm.SlfEmployee;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.model.opm.SlfUserLfbUpdateLogByRoot;
import com.aoxin.service.inter.activity.RecommendMoneyService;
import com.aoxin.service.inter.course.webCourse.ChildrenService;
import com.aoxin.service.inter.opm.UserService;
import com.aoxin.service.inter.system.CommonService;
import com.aoxin.util.AESUtil;
import com.aoxin.util.CommonUtil;
import com.aoxin.util.EmptyUtil;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.OSSUtils;
import com.aoxin.util.RedisUtil;
import com.aoxin.util.ThreadLocalUtil;
import com.aoxin.util.qrcode.QRCode;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SlfUserMapper slfUserMapper;

    @Autowired
    private RecommendMoneyService RecommendMoneyService;

    @Autowired
    private ChildrenService childrenService;
    @Autowired
    SlfUserLfbUpdateLogByRootMapper slfUserLfbUpdateLogByRootMapper;
    
    
    private static final String EXTENSION_LINK = "http://pay.sandcubes.com/slf/register.html?recommendId=";

    @Override
    @Transactional
    public void deleteUserByIds(List<Integer> userIds) {
        Assert.notEmpty(userIds, String.format(ErrorUtil.PARAMETER_NULL, "userIds"));
        this.slfUserMapper.deleteByPrimaryKeys(userIds);
    }

    @Override
    @Transactional
    public SlfUser insertUser(UserAndChildrenDto record) throws NumberFormatException, IllegalAccessException, ParseException {
        Assert.notNull(record, String.format(ErrorUtil.PARAMETER_NULL, "record"));
        // 判断验证码是否失效
        String identifyCode = record.getIdentifyCode();
        String oidIdentifyCode = (String) RedisUtil.get(record.getPhone() + CommonService.PHONE_IDENTIFY_CODE);
        if (null == oidIdentifyCode) {
            throw new IllegalArgumentException(ErrorUtil.LOGIN_IDENTIFY_CODE_ABATE);
        }
        if (!oidIdentifyCode.equals(identifyCode)) {
            throw new IllegalArgumentException(ErrorUtil.IDENTIFY_CODE_ERROR);
        }
        RedisUtil.del(record.getPhone() + CommonService.PHONE_IDENTIFY_CODE);
        // 判断手机号是否已注册
        if (this.slfUserMapper.checkPhone(record.getPhone(), null) > 0L) {
            throw new IllegalArgumentException(ErrorUtil.HAS_PHONE);
        }
        // 用户信息
        SlfUser slfUser = new SlfUser();
        slfUser.setCreateDate(new Date());
        slfUser.setPhone(record.getPhone());
        slfUser.setName(record.getPhone());
        slfUser.setAddress(record.getAddress());
        slfUser.setState(1);
        slfUser.setPoint(0);
        //判断是否填写详细地址,如果填写地址长度大于3才能送立方比
        if (!StringUtils.isEmpty(record.getDetailedAddress()) && record.getDetailedAddress().length() > 3) {
            slfUser.setDetailedAddress(record.getDetailedAddress());
            slfUser.setAddrDelFlag(2);
            slfUser.setLfb(10D);
        } else if (!StringUtils.isEmpty(record.getDetailedAddress()) && record.getDetailedAddress().length() <= 3) {
            slfUser.setAddrDelFlag(1);
            throw new IllegalAccessException(ErrorUtil.REGISTERED_FAILURE);
        } else if (StringUtils.isEmpty(record.getDetailedAddress())) {
            //未填写详细地址
            slfUser.setDetailedAddress(record.getDetailedAddress());
            slfUser.setAddrDelFlag(0);
            slfUser.setLfb(0D);
        } else {
            System.out.println(ErrorUtil.ADDR_ERROR);
            throw new IllegalArgumentException(ErrorUtil.ADDR_ERROR);
        }
        slfUser.setVipLevel(0);
        this.slfUserMapper.insertSelective(slfUser);

        // 生成二维码
        QRCode qrCode = new QRCode();
        String imgPath = CommonUtil.getFilePath() + File.separator + slfUser.getName() + slfUser.getUserId() + ".png";
        // TODO 个人中心需要展示推广链接，可能需要存表
        qrCode.encoderQRCode(EXTENSION_LINK + AESUtil.encrypt(slfUser.getUserId().toString(), AESUtil.PASSWORD), imgPath, "png", 9);
        // 上传值OSS
        File file = new File(imgPath);
        String path = OSSUtils.upload(file);
        file.delete();
        slfUser.setQrCode(path);
        slfUser.setUrl(EXTENSION_LINK + AESUtil.encrypt(slfUser.getUserId().toString(), AESUtil.PASSWORD));
        //加密后的userId
        String recommendIdASC = AESUtil.encrypt(slfUser.getUserId().toString(), AESUtil.PASSWORD);
        slfUser.setRecommendId(recommendIdASC);
        this.slfUserMapper.updateByPrimaryKeySelective(slfUser);

        // 孩子学校
        if (record.getChildrenName() != null && !"".equals(record.getChildrenName()) && null != record.getChildrenBirthday()) {
            SlfChildren slfChildren = new SlfChildren();
            slfChildren.setBirthday(record.getChildrenBirthday());
            System.err.println(record.getChildrenBirthday());
            slfChildren.setCreateDate(new Date());
            String schoolName = slfUserMapper.querySchoolName(record.getSchoolId());
            slfChildren.setName(record.getChildrenName());
            slfChildren.setSchoolId(record.getSchoolId());
            slfChildren.setSex(record.getSex());
            slfChildren.setSchoolName(schoolName);
            slfChildren.setUserId(slfUser.getUserId());
            slfChildren.setUserName(slfUser.getName());
            if (record.getWeight() != null) {
                slfChildren.setWeight(record.getWeight());
            }
            if (record.getHeight() != null) {
                slfChildren.setHeight(record.getHeight());
            }
            // 将注册的孩子设置为默认娃儿
            slfChildren.setSequence(0);
            slfUser.setLfb(slfUser.getLfb() + 40);
            this.slfUserMapper.updateByPrimaryKeySelective(slfUser);
            this.childrenService.insertChildren(slfChildren, null);
        }


        //判断推荐类型
        if (!StringUtils.isEmpty(record.getType()) &&!StringUtils.isEmpty(record.getRecommendId())) {
            //销售人员id
            Integer recommendId = Integer.parseInt(record.getRecommendId());
            //销售人员类型
            String type = record.getType();
            //添加到销售人员推荐
            SlfRecommendMoneySale slfRecommendMoneySale = new SlfRecommendMoneySale();
            slfRecommendMoneySale.setRefereeId(recommendId);
            slfRecommendMoneySale.setReferralsId(slfUser.getUserId());
            slfRecommendMoneySale.setReferralsName(slfUser.getName());
            slfRecommendMoneySale.setReferralsPhone(slfUser.getPhone());
            slfRecommendMoneySale.setType(type);
            this.RecommendMoneyService.insertRecommendMoneySale(slfRecommendMoneySale);
        } else {
            // 添加推荐关系
            // 判断是否推荐
            Integer recommendId = !EmptyUtil.objFieldIsEmpty(record, "recommendId") ? Integer.parseInt(AESUtil.decrypt(record.getRecommendId().replaceAll("2B2B%", "+"), AESUtil.PASSWORD)) : null;
            SlfUser recommend = this.slfUserMapper.selectByPrimaryKey(recommendId);
            if (null != recommend) {
                if (null != recommendId) {
                    SlfRecommendMoney slfRecommendMoney = new SlfRecommendMoney();
                    slfRecommendMoney.setRefereeId(recommendId);
                    slfRecommendMoney.setRefereeName(recommend.getName());
                    slfRecommendMoney.setReferralsId(slfUser.getUserId());
                    slfRecommendMoney.setReferralsName(slfUser.getName());
                    this.RecommendMoneyService.insertRecommendMoney(slfRecommendMoney);
                }
            }
        }

        return slfUser;
    }

    /**
     * 查询用户信息
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public SlfUser getUser(Integer userId) {
        Assert.notNull(userId, String.format(ErrorUtil.PARAMETER_NULL, "userId"));
        return this.slfUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    @Transactional
    public void updateUser(SlfUser record) {
        Assert.notNull(record, String.format(ErrorUtil.PARAMETER_NULL, "record"));
        this.slfUserMapper.updateByPrimaryKeySelective(record);
        // 同步缓存
        String token = (String) RedisUtil.get(record.getPhone() + record.getUserId());
        RedisUtil.del(token);
        RedisUtil.set(token, record);
    }

    @Override
    public List<SlfUser> getUserList(SlfUser slfUser) {

        return this.slfUserMapper.getList(slfUser);
    }

    @Override
    @Transactional
    public void updateStates(List<Integer> userIds, Integer state) {
        Assert.notEmpty(userIds, String.format(ErrorUtil.PARAMETER_NULL, "userIds"));
        Assert.notNull(state, String.format(ErrorUtil.PARAMETER_NULL, "state"));
        this.slfUserMapper.updateStates(userIds, state);
    }

    @Override
    public SlfUser getByLoginNameAndPassword(String loginName, String password) {
        Assert.notNull(loginName, ErrorUtil.LOGIN_ACCOUNT_NULL);
        return this.slfUserMapper.getUserByLoginNameAndPassword(loginName, password);
    }

    /**
     * 修改用户详细地址
     *
     * @param slfUser
     * @return
     * @throws IllegalAccessException
     */
    @Override
    public Integer updateUserInfo(SlfUser slfUser) throws IllegalAccessException {
        Integer result = 0;
        //查询当前登录用户的信息
        SlfUser user = this.slfUserMapper.selectByPrimaryKey(slfUser.getUserId());
        if (user != null) {
            if (user.getDetailedAddress() == null && slfUser.getDetailedAddress() != null) {
                //第一次填写详细地址赠送10立方比
                if (slfUser.getDetailedAddress().length() > 3) {
                    slfUser.setLfb(user.getLfb() + 10);
                } else {
                    throw new IllegalAccessException(ErrorUtil.USER_UPDATE_SUCCESS);
                }
            }
            if (slfUser.getDetailedAddress() != null && slfUser.getDetailedAddress().length() <= 3) {
                throw new IllegalAccessException(ErrorUtil.USER_UPDATE_SUCCESS);
            }
            result = slfUserMapper.updateByPrimaryKeySelective(slfUser);
            if (slfUser.getLfb() != null) {
                double lfb = slfUser.getLfb();
                if (result > 0 && (int) lfb >= 10) {
                    result = 2;
                }
            }
        } else {
            throw new IllegalAccessException(ErrorUtil.USER_NO_ONE);
        }
        return result;
    }

    @Override
    public Integer rechargeLfb(Double lfb, Integer user_id) {
        Integer result = 0;
        if (lfb != null && lfb > 0) {
            result = slfUserMapper.rechargeLfb(lfb, user_id);
        }
        return result;
    }

    /**
     * 推广查询用户
     *
     * @param phone
     * @return
     */
    @Override
    public SlfUser getExtenSionUser(String phone) {
        return slfUserMapper.getExtenSionUser(phone);
    }

	@Override
	@Transactional
	public void updateUserLfb(SlfUser slfUser) {
		//暂定超级管理员role_id为41
		//TODO lfb字段在表设计的时候被设计为double且小数点为0 所以传入的参数小数点后面的值都被省略了....前端需要加个校验 lop
		if("41".equals(ThreadLocalUtil.getEmployee().getRole())){
			SlfUser newUser=new SlfUser();
			
			//获取用户数据
			SlfUser oldUserData=slfUserMapper.selectByPrimaryKey(slfUser.getUserId());
			BigDecimal userLfb=new BigDecimal(oldUserData.getLfb().toString());
			BigDecimal addLfb=new BigDecimal(slfUser.getLfb().toString());
			BigDecimal totalLfb=userLfb.add(addLfb);
			slfUser.setLfb(totalLfb.doubleValue());
			newUser.setUserId(slfUser.getUserId());
			newUser.setLfb(totalLfb.doubleValue());
			slfUserMapper.updateByPrimaryKeySelective(newUser);
			
			SlfUserLfbUpdateLogByRoot  slfUserLfbUpdateLogByRoot=new SlfUserLfbUpdateLogByRoot();
			SlfEmployee slfEmployee=ThreadLocalUtil.getEmployee();
			//添加日志数据
			slfUserLfbUpdateLogByRoot.setEmployeeId(slfEmployee.getEmployeeId());
			slfUserLfbUpdateLogByRoot.setEmployeeName(slfEmployee.getName());
			slfUserLfbUpdateLogByRoot.setUserId(slfUser.getUserId());
			slfUserLfbUpdateLogByRoot.setUserPhone(oldUserData.getPhone());
			slfUserLfbUpdateLogByRoot.setRoleId(Integer.parseInt(ThreadLocalUtil.getEmployee().getRole()));
			slfUserLfbUpdateLogByRoot.setRoleName(slfEmployee.getRoleName());
			slfUserLfbUpdateLogByRoot.setAddLfb(addLfb.doubleValue());
			//写入日志
			slfUserLfbUpdateLogByRootMapper.insertSelective(slfUserLfbUpdateLogByRoot);
		}else{
			  throw new IllegalArgumentException(ErrorUtil.AUTHRITY);
		}
		 
	}
}
